package com.fafa.pos.dao.impl;

import android.content.ContentValues;
import android.database.Cursor;
import com.fafa.pos.dao.DBUtil;
import com.fafa.pos.dao.IConfigDao;
import com.fafa.pos.pojo.Config;

import java.util.Set;

/**
 * Created by ZhouBing on 2017/8/10.
 *
 * SQLite  --  T_CONFIG
 */
public class ConfigDaoImpl implements IConfigDao {

    private DBUtil dbUtil;

    public ConfigDaoImpl(DBUtil dbUtil) {
        this.dbUtil = dbUtil;
    }

    @Override
    public Config getConfig() {

        Config config = new Config();
        String sql = "select * from T_CONFIG";
        Cursor cursor = dbUtil.getDB().rawQuery(sql,null);
        while (cursor.moveToNext()){
            config.getProperties().put(cursor.getString(0),cursor.getString(1));
        }
        cursor.close();
        dbUtil.close();
        return config;
    }

    @Override
    public void saveConfig(Config config) {

        Set<String> keys = config.getProperties().keySet();

        for (String key:keys) {//存在更新，不存在新增

            String sql = "select * from T_CONFIG where key = ?";
            Cursor cursor = dbUtil.getDB().rawQuery(sql,new String[]{key});
            if(cursor.moveToNext()){//存在更新
                sql = "update T_CONFIG set value = ? where key = ?";
                dbUtil.getDB().execSQL(sql,new String[]{config.getProperties().get(key),key});

            }else{
                ContentValues contentValues = new ContentValues();
                contentValues.put("KEY",key);
                contentValues.put("VALUE",config.getProperties().get(key));
                dbUtil.getDB().insert("T_CONFIG",null,contentValues);
            }
            if(cursor!=null){
                cursor.close();
                cursor = null;
            }
        }
        dbUtil.close();
    }

    /**
     * 本包下可调用
     * 保存配置项
     * 存在更新
     * 不存在新增
     *
     * 谁调用谁关闭 SQLiteDatabase
     * @param key
     * @param value
     */
    void saveItem(String key, String value) {
        String sql = "select * from T_CONFIG where key = ?";
        Cursor cursor = dbUtil.getDB().rawQuery(sql,new String[]{key});
        if(cursor.moveToNext()){//存在更新
            sql = "update T_CONFIG set value = ? where key = ?";
            dbUtil.getDB().execSQL(sql,new String[]{value,key});

        }else{
            ContentValues contentValues = new ContentValues();
            contentValues.put("KEY",key);
            contentValues.put("VALUE",value);
            dbUtil.getDB().insert("T_CONFIG",null,contentValues);
        }
        if(cursor!=null){
            cursor.close();
        }
    }
}
